package ar.com.bdf.ipharma.communications.serial;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.comm.CommPortIdentifier;
import javax.comm.NoSuchPortException;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.UnsupportedCommOperationException;

public class HandlerPort {
	
	private static Map<String, SerialPort> ports = Collections.synchronizedMap(new HashMap<String, SerialPort>());
	
	public synchronized static SerialPort getInstance(String port) throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException{
		if (!ports.containsKey(port)){
			ports.put(port, HandlerPort.getPortInstance(port));
		}
		return ports.get(port);
	}
	
	
	private static SerialPort getPortInstance(String namePort) throws NoSuchPortException,
			PortInUseException, UnsupportedCommOperationException {

		CommPortIdentifier idPuerto = CommPortIdentifier.getPortIdentifier(namePort);

		SerialPort puertoSerie = (SerialPort) idPuerto.open("serialPort", 5000);
		puertoSerie.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
		
		return puertoSerie;
	}
}
